package com.ruoyi.warning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.warning.domain.entity.Event;
import com.ruoyi.warning.domain.entity.EventDetail;
import com.ruoyi.warning.domain.entity.Syslog;
import com.ruoyi.warning.domain.query.SyslogQuery;
import com.ruoyi.warning.mapper.EventMapper;
import com.ruoyi.warning.mapper.SyslogMapper;
import com.ruoyi.warning.service.IEventDetailService;
import com.ruoyi.warning.service.IEventService;
import com.ruoyi.warning.service.ISyslogService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chenhc
 * @since 2025-05-19
 */
@Service
public class SyslogServiceImpl extends ServiceImpl<SyslogMapper, Syslog> implements ISyslogService {

    @Resource
    private IEventService eventService;
    @Resource
    private IEventDetailService eventDetailService;
    @Resource
    private EventMapper eventMapper;
    @Override
    public Object getPage(SyslogQuery query) {
        Page<Syslog> page = PageHelper.startPage(query.getPageNum(),query.getPageSize());
        LambdaQueryWrapper<Syslog> wrapper = new QueryWrapper<Syslog>().lambda()
                .eq(query.getDeviceId() != null,Syslog::getDeviceId,query.getDeviceId())
                .ge(query.getStartTime()!=null,Syslog::getTimestamp,query.getStartTime())
                .le(query.getEndTime()!=null,Syslog::getTimestamp,query.getEndTime())
                .eq(query.getLevel()!=null,Syslog::getLevel,query.getLevel())
                .orderByDesc(Syslog::getTimestamp);
        List<Syslog> list = this.list(wrapper);
        TableDataInfo tableDataInfo = new TableDataInfo(list, page.getTotal());
        return tableDataInfo;
    }

    public static void main(String[] args) {
        try {
            // 构建命令数组（避免空格分割问题）
            String[] cmd = {"nc", "-u", "-z", "-v", "172.30.30.112", "161"};

            // 创建进程
            Process process = Runtime.getRuntime().exec(cmd);

            // 读取标准输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            // 读取错误输出
            BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            while ((line = errorReader.readLine()) != null) {
                System.err.println(line);
            }

            // 等待进程结束并获取退出码
            int exitCode = process.waitFor();
            System.out.println("Exit Code: " + exitCode);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Scheduled(cron = "0 0 0 * * ?")
    @Override
    public void deleteSyslog() {
        System.out.println("任务在每天 0 点执行");
        //清理30天前的日志
        LambdaQueryWrapper<Syslog> wrapper = new QueryWrapper<Syslog>().lambda()
               .le(Syslog::getTimestamp,java.time.LocalDateTime.now().minusDays(30));
        this.remove(wrapper);
        //清理半年前的事件和细节
        LambdaQueryWrapper<Event> eventWrapper = new QueryWrapper<Event>().lambda()
                .le(Event::getCreateTime,java.time.LocalDateTime.now().minusMonths(1));
//        eventService.remove(eventWrapper);
        eventMapper.delete(eventWrapper);
        LambdaQueryWrapper<EventDetail> eventDWrapper = new QueryWrapper<EventDetail>().lambda()
                .le(EventDetail::getCreateTime,java.time.LocalDateTime.now().minusMonths(1));
        eventDetailService.remove(eventDWrapper);
    }
}
